﻿using Microsoft.Vbe.Interop;
using System.Reflection;
using CommandBar = Microsoft.Office.Core.CommandBar;
using CommandBarButton = Microsoft.Office.Core.CommandBarButton;
using MsoButtonStyle = Microsoft.Office.Core.MsoButtonStyle;
using MsoControlType = Microsoft.Office.Core.MsoControlType;

namespace MyCusTools
{
    public class VbeMenu_Cls:IExcelAddIn
    {
        private CommandBar MenuBar; // 和插件同声明周期
        public void AutoClose()
        {
            MenuBar.Delete();
        }

        public void AutoOpen()
        {
            dynamic ExcelApp = ExcelDnaUtil.Application;
            VBE Vbe = ExcelApp.VBE;
            MenuBar = Vbe.CommandBars.Add("Cus_Menu", 1);
            if (MenuBar == null)
            {
                MessageBox.Show("未找到VBE菜单栏！");
                return;
            }
            
            MenuBar.Visible = true;
            CommandBarButton Button = (CommandBarButton)MenuBar.Controls.Add(
                MsoControlType.msoControlButton,
                Before:1);

            Button.Caption = "自定义菜单"; // 显示的Text
            Button.Tag = "Cus_Menu"; // 所属的Tag
            Button.Style = MsoButtonStyle.msoButtonCaption;
            Button.Click += static (CommandBarButton ctrl, ref bool cancel) =>
            {
                ////返回选中的代码块
                //int a, b, c, d;
                //dynamic ExcelApp = ExcelDnaUtil.Application;
                //VBE Vbe = ExcelApp.VBE;
                //Vbe.ActiveCodePane.GetSelection(out a, out b, out c, out d);
                //string Con = null;
                //for (int i = a; i <= c; i++)
                //{
                //    Con = Con + Vbe.ActiveCodePane.CodeModule.Lines[i, 1] + "\n";
                //}

                //MessageBox.Show($"首行{a},首列{b},尾行{c},尾列{d}" + "\n"
                //    + $"内容{Con}");
                //MessageBox.Show("VBE 菜单已点击！");
            };

            //int Counter;
            //Counter = Vbe.VBProjects.Item("Cus_VBA_Pro").VBComponents.Count;
            //for (int i = 1; i <= Counter; i++)
            //{
            //    MessageBox.Show($"{i}:" +"\n"
            //        + Vbe.ActiveVBProject.VBComponents.Item(i).Name+"\n"
            //        + Vbe.ActiveVBProject.VBComponents.Item(i).Type);
            //}
        }
    }
}
